package com.mall.controller;

import com.github.pagehelper.PageHelper;
import com.mall.common.resp.ResponseResult;
import com.mall.entity.Article;
import com.mall.service.ArticleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author xyl
 * @date 2021-02-25 17:39
 */
@Api(tags = "文章接口")
@RestController
@RequestMapping("article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @ApiOperation("添加文章")
    @PreAuthorize("hasRole('ADMIN') or hasRole('COMMON_ADMIN')")
    @PostMapping("add")
    public ResponseResult add(@RequestBody @Validated Article article){
        return  ResponseResult.toResponse(articleService.add(article));
    }

    @ApiOperation("修改")
    @PreAuthorize("hasRole('ADMIN') or hasRole('COMMON_ADMIN')")
    @PostMapping("modify")
    public ResponseResult modify(@RequestBody Article article){
        if (ObjectUtils.isEmpty(article.getArticleId())) {
            return ResponseResult.error("文章id不能为null");
        }
        return ResponseResult.toResponse(articleService.modify(article));
    }

    @ApiOperation("删除")
    @PreAuthorize("hasRole('ADMIN') or hasRole('COMMON_ADMIN')")
    @PostMapping("remove")
    public ResponseResult remove(@RequestParam Integer articleId){
        return ResponseResult.toResponse(articleService.remove(articleId));
    }

    @ApiOperation("添加浏览量")
    @GetMapping("/increase/pageView")
    public ResponseResult increasePageView(@RequestParam Integer articleId){
        return ResponseResult.toResponse(articleService.increasePageView(articleId));
    }


    @ApiOperation("列表")
    @GetMapping("/page/list")
    public List<Article> list(@RequestParam(required = false) Integer pageNumber,@RequestParam(required = false) String keyWord){
        if(ObjectUtils.isNotEmpty(pageNumber)){
            PageHelper.startPage(pageNumber,10);
        }
        return articleService.list(keyWord);
    }

    @ApiOperation("根据文章id获取文章内容")
    @GetMapping("/get")
    public ResponseResult get(@RequestParam Integer articleId){
        return ResponseResult.success(articleService.get(articleId));
    }
}